//
//  ADJgSDKNativeAdContainer.m
//  AnyThinkSDKDemo
//
//  Created by 刘娟 on 2024/9/25.
//  Copyright © 2024 抽筋的灯. All rights reserved.
//

#import "ADJgSDKNativeAdContainer.h"
#import <AnyThinkNative/AnyThinkNative.h>
#import "ADJgSDKNativeCustomEvent.h"
#import <ADJgKit/UIFont+ADJgKit.h>
#import <ADJgKit/UIColor+ADJgKit.h>

@interface ADJgSDKNativeAdContainer()<ADJgSDKNativeAdDelegate>

@property(nonatomic, strong) ADJgSDKNativeAd *NativeAd;

@property(nonatomic, assign) CGFloat bidPrice;

@property(nonatomic, assign) CGFloat bidFloor;

@property(nonatomic, assign) CGSize size;

@end

@implementation ADJgSDKNativeAdContainer
-(void)setDelegate:(id<ADJgSDKNativeAdDelegate>)delegate{
    self.NativeAd.delegate = delegate;
}
- (void)setController:(UIViewController *)controller{
    self.NativeAd.controller = controller;
}
// MARK: - Init
-(instancetype)initPosId:(NSString *)posId delegate:(id<ADJgSDKNativeAdDelegate>)delegate size:(CGSize)size{
    self = [super init];
    if(self){
        self.NativeAd = [[ADJgSDKNativeAd alloc] initWithAdSize:size];
        self.NativeAd.posId = posId;
        self.NativeAd.delegate = delegate;
        if (delegate == nil) {
            self.NativeAd.delegate = self;
        }
        self.size = size;
    }
    return self;
}
- (void)loadNativeAdWithCount:(int)count{
    if(self.NativeAd){
        [self.NativeAd load:count];
    }
}
-(void)close{
    _NativeAd = nil;
}
- (NSInteger)getBidPrice{
    return _bidPrice;
}
- (NSInteger)getBidFloor{
    
    return _bidFloor;
}
// 自渲染样式示例 具体样式自行调整
- (void)setUpUnifiedTopImageNativeAdView:(UIView<ADJgAdapterNativeAdViewDelegate> *)adView {
    // 设计的adView实际大小，其中宽度和高度可以自己根据自己的需求设置
    CGFloat adWidth = self.size.width;
    CGFloat adHeight = (adWidth - 17 * 2) / 16.0 * 9 + 67 + 38;
    adView.frame = CGRectMake(0, 0, adWidth, adHeight);
    
    // 显示logo图片（必要）
    if(![adView.adjg_platform isEqualToString:ADJgAdapterPlatformGDT]) { // 优量汇（广点通）会自带logo，不需要添加
        UIImageView *logoImage = [UIImageView new];
        [adView addSubview:logoImage];
        [adView adjg_platformLogoImageDarkMode:NO loadImageBlock:^(UIImage * _Nullable image) {
            CGFloat maxWidth = 40;
            CGFloat logoHeight = maxWidth / image.size.width * image.size.height;
            logoImage.frame = CGRectMake(adWidth - maxWidth, adHeight - logoHeight, maxWidth, logoHeight);
            logoImage.image = image;
        }];
    }
    
    // 设置标题文字（可选，但强烈建议带上）
    UILabel *titlabel = [UILabel new];
    [adView addSubview:titlabel];
    titlabel.font = [UIFont adjg_PingFangMediumFont:14];
    titlabel.textColor = [UIColor adjg_colorWithHexString:@"#333333"];
    titlabel.numberOfLines = 2;
    titlabel.text = adView.data.title;
    CGSize textSize = [titlabel sizeThatFits:CGSizeMake(adWidth - 17 * 2, 999)];
    titlabel.frame = CGRectMake(17, 16, adWidth - 17 * 2, textSize.height);
    
    CGFloat height = textSize.height + 16 + 15;
    
    // 设置主图/视频（主图可选，但强烈建议带上,如果有视频试图，则必须带上）
    CGRect mainFrame = CGRectMake(17, height, adWidth - 17 * 2, (adWidth - 17 * 2) / 16.0 * 9);
    if(adView.data.shouldShowMediaView) {
        UIView *mediaView = [adView adjg_mediaViewForWidth:mainFrame.size.width];
        mediaView.frame = mainFrame;
        [adView addSubview:mediaView];
    } else {
        UIImageView *imageView = [UIImageView new];
        imageView.backgroundColor = [UIColor adjg_colorWithHexString:@"#CCCCCC"];
        [adView addSubview:imageView];
        imageView.frame = mainFrame;
        NSString *urlStr = adView.data.imageUrl;
        if(urlStr.length > 0) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
                UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    imageView.image = image;
                });
            });
        }
    }
    
    // 设置广告标识（可选）
    height += (adWidth - 17 * 2) / 16.0 * 9 + 9;
    UILabel *adLabel = [[UILabel alloc]init];
    adLabel.backgroundColor = [UIColor adjg_colorWithHexString:@"#CCCCCC"];
    adLabel.textColor = [UIColor adjg_colorWithHexString:@"#FFFFFF"];
    adLabel.font = [UIFont adjg_PingFangLightFont:12];
    adLabel.text = @"广告";
    [adView addSubview:adLabel];
    adLabel.frame = CGRectMake(17, height, 36, 18);
    adLabel.textAlignment = NSTextAlignmentCenter;
    
    // 设置广告描述(可选)
    UILabel *descLabel = [UILabel new];
    descLabel.textColor = [UIColor adjg_colorWithHexString:@"#333333"];
    descLabel.font = [UIFont adjg_PingFangLightFont:12];
    descLabel.textAlignment = NSTextAlignmentLeft;
    descLabel.text = adView.data.desc;
    [adView addSubview:descLabel];
    descLabel.frame = CGRectMake(17 + 36 + 4, height, self.size.width - 57 - 17 - 20, 18);
    
    // 展示关闭按钮（必要）
    UIButton *closeButton = [UIButton new];
    [adView addSubview:closeButton];
    [adView bringSubviewToFront:closeButton];
    closeButton.frame = CGRectMake(adWidth - 44, 0, 44, 44);
    UIImage *closeImg = [UIImage imageNamed:@"icon_webview_close" inBundle:[NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"AnyThinkSDK" ofType:@"bundle"]] compatibleWithTraitCollection:nil];
    [closeButton setImage:closeImg forState:UIControlStateNormal];
    // jgads_close方法为协议中方法 直接添加target即可 无需实现
    [closeButton addTarget:adView action:@selector(adjg_close) forControlEvents:UIControlEventTouchUpInside];
    
}
#pragma mark -- ADJgSDKNativeAdDelegate
- (void)adjg_nativeAdViewRenderOrRegistSuccess:(UIView<ADJgAdapterNativeAdViewDelegate> *)adView{
//    if (adView.renderType == ADJgAdapterRenderTypeNative) {
    NSMutableDictionary *asset = [NSMutableDictionary dictionary];
    asset[kATAdAssetsCustomEventKey] = [ADJgSDKNativeCustomEvent new];
    asset[kATAdAssetsCustomObjectKey] = adView;
    asset[@"nativeexpress_manager"] = self;
    self.controller = [UIApplication sharedApplication].keyWindow.rootViewController;
    asset[kATNativeADAssetsNativeExpressAdViewWidthKey] = [NSString stringWithFormat:@"%lf",adView.frame.size.width];
    asset[kATNativeADAssetsNativeExpressAdViewHeightKey] = [NSString stringWithFormat:@"%lf",adView.frame.size.height];
    self.assets = [NSMutableArray array];
    [self.assets addObject:asset];
//    }
}
/**
 *  开屏广告素材加载成功
 */
- (void)adjg_nativeAdSucessToLoad:(ADJgSDKNativeAd *)nativeAd adViewArray:(NSArray<__kindof UIView<ADJgAdapterNativeAdViewDelegate> *> *)adViewArray{
    if(adViewArray.count > 0){
        UIView<ADJgAdapterNativeAdViewDelegate> *bidAdView = adViewArray.firstObject;
        ADJgSDKExtInfo *extInfo = [bidAdView adjg_extInfo];
        _bidPrice = extInfo.ecpm.floatValue;
        
        if (bidAdView.renderType == ADJgAdapterRenderTypeExpress) {
        NSMutableDictionary *asset = [NSMutableDictionary dictionary];
        asset[kATAdAssetsCustomEventKey] = [ADJgSDKNativeCustomEvent new];
        asset[kATAdAssetsCustomObjectKey] = bidAdView;
        asset[@"nativeexpress_manager"] = self;
        self.controller = [UIApplication sharedApplication].keyWindow.rootViewController;
        asset[kATNativeADAssetsNativeExpressAdViewWidthKey] = [NSString stringWithFormat:@"%lf",bidAdView.frame.size.width];
        asset[kATNativeADAssetsNativeExpressAdViewHeightKey] = [NSString stringWithFormat:@"%lf",bidAdView.frame.size.height];
        asset[kATNativeADAssetsIsExpressAdKey] = @"1";
        self.assets = [NSMutableArray array];
        [self.assets addObject:asset];
        [bidAdView adjg_registViews:@[bidAdView]];
        }else{
            [self setUpUnifiedTopImageNativeAdView:bidAdView];
            [bidAdView adjg_registViews:@[bidAdView]];
        }
        
        if ([self.containerDelegate respondsToSelector:@selector(jgsdkContainer_jgsdkNativeAdDidLoad:withPrice:)]) {
            [self.containerDelegate jgsdkContainer_jgsdkNativeAdDidLoad:self withPrice:_bidPrice];
        }}else{
            
        }
#if DEBUG
        NSLog(@"ADJgSDK - 信息流广告 - 加载成功");
#endif

}

/**
 *  开屏广告请求失败
 */
- (void)adjg_nativeAdFailToLoad:(ADJgSDKNativeAd *)nativeAd errorModel:(ADJgAdapterErrorDefine *)errorModel{
    if ([self.containerDelegate respondsToSelector:@selector(jgsdkContainer_jgsdkNativeAdFailLoadError:)]) {
        [self.containerDelegate jgsdkContainer_jgsdkNativeAdFailLoadError:nil];
    }
#if DEBUG
        NSLog(@"ADJgSDK - 信息流广告 - 加载失败");
#endif
}
@end

